<!--
 * @Author: Li Zengkun
 * @Date: 2022-08-15 20:13:00
 * @LastEditors: Li Zengkun
 * @LastEditTime: 2022-08-18 12:16:51
 * @Description: 确认订单页面
-->
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="../css/reset.css">
    <link rel="stylesheet" href="../css/style.css">
    <link rel="stylesheet" href="../css/confirm_order.css">
    <link rel="stylesheet" href="../node_modules/font-awesome/css/font-awesome.min.css">
    <title>确认订单</title>
</head>

<body>
    <header>
        <a id="return" href="javascript:history.back()">
            <i class="fa fa-chevron-left" aria-hidden="true"></i>
        </a>
        确认订单
        <p></p>
    </header>

    <div class="content-box">
        <div class="order-item">
            <p>寄送至</p>
            <a href="./select_address.html">
                <i class="fa fa-chevron-right" aria-hidden="true"></i>
            </a>
        </div>
        <div class="envelope">
            <div class="head">
                <span id="name">请选择收货地址...</span>
                <span id="tel"></span>
            </div>
            <p id="address" class="address"></p>
            <div id="isDefault" class="default">默认</div>
        </div>

        <ul id="goods-list" class="goods-list">
            <!-- 插入位置 -->
        </ul>

        <div class="order-item">
            <p>商品合计</p>
            <p>￥<span id="goods-sum-price">999.00</span></p>
        </div>
        <div class="order-item">
            <p>运费</p>
            <p>￥<span id="freight-price">0.00</span></p>
        </div>
        <div id="coupon" class="order-item">
            <p>优惠券：</p>
            <p id="coupon-name">未选择</p>
            <p>
                <span id="coupon-num">0</span>张
            </p>
        </div>
        <div id="remarks" class="order-item">
            <p>备注：</p>
            <input type="text" placeholder="填写备注...">
        </div>

    </div>

    <footer>
        <div class="text">
            合计:￥
            <span id="sum-price">666</span>
        </div>
        <div class="btn" id="create-order-btn">
            下单
        </div>
    </footer>

    <!-- 加载中... -->
    <div class="loading">
        <img class="rotate-center" src="../img/loading.svg" alt="">
        <p>加载中...</p>
    </div>

    <!-- 提示 tip -->
    <span id="tip" class="tip"></span>

    <!-- <iframe src="./select_address.html"></iframe> -->
</body>



<script src="../js/axios.min.js"></script>
<script src="../js/axios_config.js"></script>
<script src="../js/api.js"></script>
<script>
    let oLoading = document.querySelector('.loading')
    let oGoodsList = document.querySelector('#goods-list')
    let oGoodsSumPrice = document.querySelector("#goods-sum-price")
    let oName = document.querySelector("#name")
    let oTel = document.querySelector("#tel")
    let oAddress = document.querySelector("#address")
    let oIsDefault = document.querySelector("#isDefault")
    let oSunPrice = document.querySelector("#sum-price")
    let oFreight = document.querySelector("#freight-price")
    let oCreateOrderBtn = document.querySelector("#create-order-btn")
    let oReturnBtn = document.querySelector("#return")

    // let url = new URL(location.href)
    let confirmOrderGoods = JSON.parse(sessionStorage.getItem('confirmOrderGoods'))

    console.log(confirmOrderGoods);

    let payment = confirmOrderGoods.payment
    let goodsIdList = confirmOrderGoods.goodsList
    let address = null

    init()

    async function init() {
        console.log(goodsIdList);
        let obj = await getSettleOrder(goodsIdList)
        console.log(obj);
        let goodsList = obj.goods
        console.log(goodsList);
        address = obj.address
        if (!address) {
            address = await getAddressById(sessionStorage.getItem('newSelectAddressId'))
                // sessionStorage.removeItem('newSelectAddressId')
        }

        // 获取新选择的地址
        // if (sessionStorage.getItem('newSelectAddressId')) {
        // } else {
        //     address = obj.address
        //     console.log(address);
        // }

        // 显示商品合计
        oGoodsSumPrice.innerText = payment.toFixed(2)

        // 显示地址
        if (address) {
            oName.innerText = address.name
            oTel.innerText = address.tel
            oAddress.innerText = `${address.province_name} ${address.city_name} ${address.county_name} ${address.town_name} ${address.street}`
            oIsDefault.style.display = address.isDefault === 1 ? 'block' : 'none'
        } else {
            oIsDefault.style.display = 'none'

        }

        // 初始化商品列表
        await goodsList.forEach(async(item) => {
            let goodsDetail = await getGoodsDetail(item.id)
            let itemHTML = `<li class="goods-item" data-id="${item.id}">
                <div class="img-box">
                    <img class="goods-img" src="${item.img_md}" alt="">
                </div>
                <div class="text-content">
                    <p class="name" id="goods-name">${item.name}</p>
                    <p class="type">
                        <span id="goods-type">${item.type==undefined?'默认':item.type}</span> ×
                        <span id="goods-num">${item.goods_num}</span>
                    </p>
                    <p class="price">￥${item.price}</p>
                </div>
            </li>`
            oGoodsList.insertAdjacentHTML('beforeend', itemHTML)
        });

        // 合计
        oSunPrice.innerText = (payment + parseFloat(oFreight.innerText)).toFixed(2)

        // 取消加载动画
        oLoading.style.display = 'none'


        // 添加下单点击事件
        oCreateOrderBtn.addEventListener('click', async() => {
            console.log("下单");
            let goodsIdNum = []
            goodsList.forEach((item) => {
                goodsIdNum.push({
                    id: item.id,
                    num: item.goods_num
                })
            })
            console.log(goodsIdNum);
            let resp = await createOrder(payment, address.id, goodsIdNum)
            if (!resp.status) {
                let outOfStockId = resp.data.id
                let outOfStockName = goodsList.filter((item) => {
                    return item.id === outOfStockId
                })[0].name
                openTip(`${outOfStockName} <p style="color:red">库存不足</p>`)
                return
            }
            if (resp.status) {
                // location.href = './pay.html'
                openTip("下单成功")
                setTimeout(() => {
                    window.location.replace(document.referrer);
                }, 3000);
            }
        })

    }

    /**
     * @description: 提交订单->生成订单
     * @return {*}
     * @param {*} payment Number	支付金额,小数点至2位;
     * @param {*} addressId Number 	收货地址id;
     * @param {*} goodList  Object[] 商品数组,包含每一个商品的id,数量，例：[{id:15,num:1},{id:16,num:2}];
     */
    async function createOrder(payment, addressId, goodsList) {
        let result = null
        await axios.post('/order/create', {
            payment: payment,
            addressId: addressId,
            goodsList: goodsList
        }).then((resp) => {
            result = resp
        })
        return result
    }

    /**
     * @description: 获取"确认订单"页面的数据
     * @return {*} 返回"确认订单"页面的数据
     * @param {*} goods Number[] 欲购买商品id，格式：[id1,id2,id3];
     */
    async function getSettleOrder(goods) {
        let result = null
        await axios.post('/order/settle', {
            goods: goods,
        }).then(resp => {
            console.log(resp);
            if (resp.status) {
                result = resp.data
            }
        })
        return result
    }

    /**
     * @description: 根据 id 获取收货地址信息
     * @return {*} result(Object) 收货地址信息
     * @param {*} id   地址 id
     */
    async function getAddressById(id) {
        let result = null
        await axios.get('/address', {
            params: {
                id: id,
            }
        }).then((resp) => {
            if (resp.status) {
                result = resp.data
            }
        })
        return result
    }

    /**
     * @description: 获取商品详情
     * @return {*}  result 商品详情
     * @param {*} id 商品id
     */
    async function getGoodsDetail(id) {
        let result = null
        await axios.get('/goods/detail', {
            params: {
                id: id
            }
        }).then((resp) => {
            if (resp.status) {
                result = resp.data
            }
        })
        return result
    }

    /**
     * @description: 获取默认地址信息
     * @return {*}  result(Object) 地址信息
     */
    async function getDefaultAddress() {
        let result = null
        await axios.get('/address/list', {
            params: {
                pagesize: 1,
                pageindex: 1,
            }
        }).then((resp) => {
            result = resp.data[0]
        })
        return result
    }
</script>

</html>